import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/Login.vue'
import Reg from '@/views/Reg/Reg.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'
// 导入Home组价
import Home from '@/views/Menus/Home/Home.vue'
// 用户信息
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar'
import UserPwd from '@/views/Menus/User/UserPwd'

Vue.use(VueRouter)

// 防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 路由规则数组
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: Main,
    // 开启路由重定向
    redirect: '/home',
    // Home作为子路由规则
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 设置全局前置守卫,进行未登录的权限控制
// to: 到哪里去
// from: 从哪里来
// next: 是否放行(是一个函数);调用不传参表示放行;调用传入false表示不放行;调用传入路径强行跳转到指定页面
router.beforeEach((to, from, next) => {
  // whiteList: 白名单,无论是否登录都可以访问的页面
  const whiteList = ['/login', '/reg']
  if (!store.state.user.token && !whiteList.includes(to.path)) {
    Vue.prototype.$message.error('请先登录!')
    return next('/login')
  }
  next()
})

export default router
